package com.godyao.mall.user.boot.init;

import cn.hutool.core.collection.CollectionUtil;
import com.godyao.mall.core.model.oauth.OAuthConstant;
import com.godyao.mall.user.boot.service.ISysPermissionService;
import com.godyao.mall.user.common.model.SysRole;
import com.godyao.mall.user.common.model.vo.SysRolePermissionVo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户权限缓存预热
 * @author godyao
 * @date 2022/4/2
 */
@Service
public class LoadRolePermissionService implements InitializingBean {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ISysPermissionService permissionService;

    @Override
    public void afterPropertiesSet() {
        // 获取所有权限
        final List<SysRolePermissionVo> rolePermissionVos = permissionService.listRolePermission();
        rolePermissionVos.parallelStream().peek(sysRolePermissionVo -> {
            final List<String> roles = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(sysRolePermissionVo.getRoles())) {
                for (SysRole role : sysRolePermissionVo.getRoles()) {
                    roles.add(OAuthConstant.ROLE_PREFIX + role.getCode());
                }
            }
            // 放到redis中
            redisTemplate.opsForHash().put(OAuthConstant.OAUTH_URLS, sysRolePermissionVo.getUrl(), roles);
        }).collect(Collectors.toList());
    }
}
